from . import *


"""
===================================
1:生成唯一文件名;
2:文件名称检测，生成数字下标文件名;
3:获取图像宽、高、宽高比;
4:将文件夹中指定jpg图片转换为指定名称的pdf文件，并保存至指定文件夹;
5:查询本机ip地址;
6:将PDF转化为图片， 存在内存泄露;
===================================
"""


def get_ufn() -> str:
    """1:生成唯一标识符"""
    tk = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    m = hashlib.md5()
    m.update(bytes(tk, encoding='utf8'))
    return m.hexdigest()


def generate_abspath(dirname: str, basename: str) -> tuple:
    """
    2:文件名称检测，生成数字下标文件名 eg: xxx.png ->'xxx-1.png'
    :param dirname: 被检测绝对路径
    :param basename: 文件名称
    :return: index 0:abspath, 1:dirname, 2:basename
    """
    name = basename.split('.')[0]
    suffix = '.' + basename.split('.')[1]
    # 设置文件下标初始为0
    index = 1
    abspath = os.path.join(dirname, name + '-' + str(index) + suffix)
    while os.path.isfile(abspath) is True:
        index += 1
        abspath = os.path.join(dirname, name + '-' + str(index) + suffix)

    dirname = os.path.dirname(abspath)
    basename = os.path.basename(abspath)
    return abspath, dirname, basename


def get_image_size(filepath: os.path):
    """3:获取图像宽、高、宽高比"""
    img = Image.open(filepath)
    imgSize = img.size
    img.close()
    return imgSize[0], imgSize[1], imgSize[0]/imgSize[1]


def pic2pdf_2(img_path, pdf_path, img_list, pdf_name):
    """4:将文件夹中指定jpg图片转换为指定名称的pdf文件，并保存至指定文件夹"""
    doc = fitz.open()
    pic_list = [os.path.join(img_path, i) for i in img_list]

    for img in sorted(pic_list):
        imgdoc = fitz.open(img)
        pdfbytes = imgdoc.convertToPDF()
        imgpdf = fitz.open("pdf", pdfbytes)
        doc.insertPDF(imgpdf)
    doc.save(os.path.join(pdf_path, pdf_name))
    doc.close()


def get_host_ip() -> str:
    """
    5:查询本机ip地址
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


def pdf_image(imgPath, pdfPath='', prefix='', pdf_bytes=None, itype=0,
              rotation_angle=0, zoom_x=3, zoom_y=3, suffix=SUFFIX):
    """
    6:将PDF转化为图片， 存在内存泄露
    :param imgPath: 图像要保存的文件夹
    :param prefix: 图像保存前缀 ag: 'name-'
    :param pdfPath: pdf文件的路径
    :param pdf_bytes: pdf流
    :param itype: 通过哪种方式读取， 默认为通过路径
    :param rotation_angle: 旋转角度
    :param zoom_x: x方向的缩放系数
    :param zoom_y: y方向的缩放系数
    :param suffix: 图片存储格式
    :return: pdf名
    # pdf_image(pdf_image_path, pdf_path)
    # pdf_image(pdf_image_path, itype=1, pdf_bytes=pdf_bytes)
    """
    if itype == 0:
        # 打开PDF文件
        pdf = fitz.open(pdfPath)
        for pg in range(0, pdf.pageCount):
            page = pdf[pg]  # fitz.fitz.Page
            # 设置缩放和旋转系数
            trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)
            pm = page.getPixmap(matrix=trans, alpha=False)
            # 开始写图像

            image_path = os.path.join(imgPath, (prefix + str(pg + 1) + suffix))
            # /Volumes/程序员/PythonProject/Dome/media/pdf_image/0.png
            pm.writePNG(str(image_path))
        pdf.close()
    else:
        pdf = fitz.Document(stream=pdf_bytes, filetype='pdf')
        for pg in range(0, pdf.pageCount):
            page = pdf[pg]  # fitz.fitz.Page
            # 设置缩放和旋转系数
            trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)
            pm = page.getPixmap(matrix=trans, alpha=False)
            # 开始写图像

            image_path = os.path.join(imgPath, (prefix + str(pg + 1) + suffix))
            # /Volumes/程序员/PythonProject/Dome/media/pdf_image/0.png
            pm.writePNG(str(image_path))
        pdf.close()
    return image_path